package logic

import (
	"context"
	"fmt"
	"hotel/model/mysql"
	"hotel/model/redisInit"
	"hotel/pkg"

	"hotel/hotelrpc/hotelrpc"
	"hotel/hotelrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *hotelrpc.UserLoginRequest) (*hotelrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	loginGet := redisInit.Rdb.Get("sendSmsLogin" + in.Phone)
	if loginGet.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("验证码不正确")
	}
	var hotel mysql.Hotel
	mysql.DB.Debug().Where("phone = ?", in.Phone).Find(&hotel)
	if hotel.ID == 0 {
		return nil, fmt.Errorf("该账号不存在,请前去注册")
	}
	if hotel.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码错误")
	}
	redisInit.Rdb.Del("sendSmsLogin" + in.Phone)
	return &hotelrpc.UserLoginResponse{
		Id: int64(hotel.ID),
	}, nil
}
